package com.ycb.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.ycb.mapper.OrderMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;

public class MybatisUtil {
 
	static String driver = "com.mysql.cj.jdbc.Driver";
	static String url = "jdbc:mysql://127.0.0.1:3306/db_temp?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
	static String username = "root";
	static String password = "root";
	private static SqlSessionFactory sqlSessionFactory ;

	public static SqlSession getSqlSession(boolean autoCommit) throws SQLException, IOException {
		if (sqlSessionFactory == null){
			DataSource dataSource = getShardingSphereDataSource();
			TransactionFactory transactionFactory = new JdbcTransactionFactory();
			MybatisSqlSessionFactoryBuilder builder = new MybatisSqlSessionFactoryBuilder();
			Environment environment = new Environment("development", transactionFactory, dataSource);
			MybatisConfiguration mybatisConfiguration = new MybatisConfiguration(environment);
			mybatisConfiguration.addMapper(OrderMapper.class);
			sqlSessionFactory = builder.build(mybatisConfiguration);
		}
		return sqlSessionFactory.openSession(autoCommit);
	}


	public static OrderMapper getOrderMapper() throws SQLException, IOException {
		return getSqlSession(true).getMapper(OrderMapper.class);
	}

	public static DataSource getShardingSphereDataSource() throws SQLException, IOException {
		byte[] yamlData = ResourceUtil.readBytes("sharding-jdbc.yaml");
		DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlData);
//		SeataDataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
		return dataSource;
	}

	public static DataSource defaultDataSource(){
		DataSource dataSource = new PooledDataSource(driver,url,username,password);
		return dataSource;
	}

}